<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户行为分析实时数据看板</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
    <script src="https://cdn.jsdelivr.net/npm/flatpickr/dist/l10n/zh.js"></script>

    <!-- Tailwind配置 - 与RFM分析页面保持一致 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#36CFC9',
                        accent: '#722ED1',
                        warning: '#FF7D00',
                        danger: '#F53F3F',
                        success: '#52C41A',
                        'neutral-100': '#F2F3F5',
                        'neutral-200': '#E5E6EB',
                        'neutral-300': '#C9CDD4',
                        'neutral-400': '#86909C',
                        'neutral-500': '#4E5969',
                        'neutral-600': '#272E3B',
                        'neutral-700': '#1D2129',
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                    boxShadow: {
                        'card': '0 2px 8px rgba(0, 0, 0, 0.08)',
                        'card-hover': '0 4px 16px rgba(0, 0, 0, 0.12)',
                    }
                },
            }
        }
    </script>

    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .card-transition {
                transition: all 0.3s ease;
            }
            .scrollbar-hide::-webkit-scrollbar {
                display: none;
            }
            .scrollbar-hide {
                -ms-overflow-style: none;
                scrollbar-width: none;
            }
            .progress-ring {
                transform: rotate(-90deg);
                transform-origin: 50% 50%;
            }
            .perspective-1000 {
                perspective: 1000px;
            }
            .preserve-3d {
                transform-style: preserve-3d;
            }
            .hover-lift {
                transition: transform 0.3s ease, box-shadow 0.3s ease;
            }
            .hover-lift:hover {
                transform: translateY(-3px);
                box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
            }
            .gradient-bg {
                background: linear-gradient(135deg, #165DFF 0%, #722ED1 100%);
            }
        }
    </style>
</head>
<body class="bg-neutral-100 font-inter text-neutral-700">
    <!-- 顶部导航栏 - 与RFM分析页面保持一致 -->
    <header class="bg-white shadow-sm sticky top-0 z-50">
        <div class="container mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between items-center h-16">
                <div class="flex items-center">
                    <i class="fa fa-bar-chart text-primary text-2xl mr-2"></i>
                    <span class="text-xl font-bold text-neutral-700">用户分析平台</span>
                </div>
                <nav class="hidden md:flex space-x-8">
                    <a href="/dashboard.html" class="text-primary font-medium border-b-2 border-primary pb-0.5 flex items-center">
                        <i class="fa fa-dashboard mr-1"></i> 数据看板
                    </a>
                    <a href="/rfm_segmentation" class="text-neutral-500 hover:text-primary transition-colors flex items-center">
                        <i class="fa fa-users mr-1"></i> RFM分群管理
                    </a>
                    <a href="/prediction_monitoring" class="text-neutral-500 hover:text-primary transition-colors flex items-center">
                        <i class="fa fa-line-chart mr-1"></i> 预测模型监控
                    </a>
                </nav>
                <div class="flex items-center space-x-4">
                    <div class="flex items-center space-x-2" id="refreshControls">
                        <button id="refreshBtn" class="bg-primary hover:bg-primary/90 text-white px-3 py-1.5 rounded-md text-sm flex items-center transition-all">
                            <i class="fa fa-refresh mr-1"></i> 刷新
                        </button>
                        <div class="relative">
                            <select id="refreshInterval" class="bg-neutral-100 border border-neutral-200 text-neutral-700 rounded-md text-sm px-3 py-1.5 appearance-none focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none transition-all">
                                <option value="0">不自动刷新</option>
                                <option value="30">30秒</option>
                                <option value="60">1分钟</option>
                                <option value="300">5分钟</option>
                                <option value="600">10分钟</option>
                            </select>
                            <i class="fa fa-chevron-down absolute right-3 top-1/2 -translate-y-1/2 text-xs text-neutral-400 pointer-events-none"></i>
                        </div>
                    </div>

                    <div class="flex items-center space-x-1 text-sm text-neutral-500">
                        <span id="lastUpdateTime">最后更新: 加载中...</span>
                    </div>
                </div>
            </div>
        </div>
    </header>

    <!-- 错误提示区域 - 与RFM分析页面保持一致 -->
    <div id="error-container" class="container mx-auto px-4 sm:px-6 lg:px-8 py-2 hidden">
        <div id="error-message" class="bg-danger/10 border border-danger/30 text-danger px-4 py-3 rounded-md flex items-center">
            <i class="fa fa-exclamation-circle mr-2"></i>
            <span></span>
        </div>
    </div>

    <!-- 页面标题区域 - 与RFM分析页面保持一致的风格 -->
    <header class="bg-gradient-to-r from-primary to-accent text-white py-12 md:py-20">
        <div class="container mx-auto px-4 sm:px-6 lg:px-8">
            <h1 class="text-3xl md:text-4xl font-bold mb-2">用户行为分析实时数据看板</h1>
            <p class="text-white/80 max-w-3xl">实时监控用户访问、购买等行为数据，分析用户活跃模式，助力业务决策</p>
        </div>
    </header>

    <!-- 主内容区 -->
    <main class="container mx-auto px-4 sm:px-6 lg:px-8 py-6 -mt-8 relative z-10">
        <!-- 筛选控件区域 - 卡片式设计与RFM页面保持一致 -->
        <div class="bg-white rounded-lg shadow-card p-5 mb-6 card-transition hover:shadow-card-hover">
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                <div>
                    <label class="block text-sm font-medium text-neutral-500 mb-1.5">时间范围</label>
                    <div class="relative">
                        <input id="dateRangePicker" type="text" class="w-full border border-neutral-200 rounded-md px-3 py-2 text-sm focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none transition-all" placeholder="选择日期范围">
                        <i class="fa fa-calendar absolute right-3 top-1/2 -translate-y-1/2 text-neutral-400"></i>
                    </div>
                </div>

                <div>
                    <label class="block text-sm font-medium text-neutral-500 mb-1.5">月份选择</label>
                    <div class="flex space-x-2">
                        <select id="monthSelect" class="flex-1 border border-neutral-200 rounded-md px-3 py-2 text-sm focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none transition-all">
                            <option value="11">2017年11月</option>
                            <option value="12">2017年12月</option>
                        </select>
                        <select id="yearSelect" class="w-28 border border-neutral-200 rounded-md px-3 py-2 text-sm focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none transition-all">
                            <option value="2017">2017年</option>
                        </select>
                    </div>
                </div>

                <div>
                    <label class="block text-sm font-medium text-neutral-500 mb-1.5">商品类目筛选</label>
                    <div class="relative">
                        <select id="categoryFilter" class="w-full border border-neutral-200 rounded-md px-3 py-2 text-sm focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none transition-all" multiple>
                            <!-- 类目选项将通过JavaScript动态加载 -->
                            <option value="all">全部类目</option>
                        </select>
                        <div class="absolute right-3 top-1/2 -translate-y-1/2 flex space-x-1 pointer-events-none">
                            <i class="fa fa-search text-neutral-400"></i>
                            <i class="fa fa-chevron-down text-neutral-400"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 数据概览卡片 - 与RFM页面保持一致的卡片风格 -->
        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6 mb-6">
            <div class="bg-white rounded-lg p-5 shadow-card card-transition hover:shadow-card-hover hover-lift">
                <div class="flex items-start justify-between">
                    <div>
                        <p class="text-neutral-500 text-sm mb-1">11月总访问量</p>
                        <h3 class="text-2xl font-bold" id="totalVisits">--</h3>
                        <p class="text-success text-xs mt-2 flex items-center">
                            <i class="fa fa-arrow-up mr-1"></i>
                            <span id="visitsGrowth">--</span>
                        </p>
                    </div>
                    <div class="bg-primary/10 p-3 rounded-lg">
                        <i class="fa fa-eye text-primary text-xl"></i>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-lg p-5 shadow-card card-transition hover:shadow-card-hover hover-lift">
                <div class="flex items-start justify-between">
                    <div>
                        <p class="text-neutral-500 text-sm mb-1">11月总购买量</p>
                        <h3 class="text-2xl font-bold" id="novemberPurchases">--</h3>
                        <p class="text-success text-xs mt-2 flex items-center">
                            <i class="fa fa-arrow-up mr-1"></i>
                            <span id="novPurchasesGrowth">--</span>
                        </p>
                    </div>
                    <div class="bg-success/10 p-3 rounded-lg">
                        <i class="fa fa-shopping-cart text-success text-xl"></i>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-lg p-5 shadow-card card-transition hover:shadow-card-hover hover-lift">
                <div class="flex items-start justify-between">
                    <div>
                        <p class="text-neutral-500 text-sm mb-1">12月总购买量</p>
                        <h3 class="text-2xl font-bold" id="decemberPurchases">--</h3>
                        <p class="text-success text-xs mt-2 flex items-center">
                            <i class="fa fa-arrow-up mr-1"></i>
                            <span id="decPurchasesGrowth">--</span>
                        </p>
                    </div>
                    <div class="bg-warning/10 p-3 rounded-lg">
                        <i class="fa fa-shopping-bag text-warning text-xl"></i>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-lg p-5 shadow-card card-transition hover:shadow-card-hover hover-lift">
                <div class="flex items-start justify-between">
                    <div>
                        <p class="text-neutral-500 text-sm mb-1">活跃用户数</p>
                        <h3 class="text-2xl font-bold" id="activeUsers">--</h3>
                        <p class="text-success text-xs mt-2 flex items-center">
                            <i class="fa fa-arrow-up mr-1"></i>
                            <span id="usersGrowth">--</span>
                        </p>
                    </div>
                    <div class="bg-secondary/10 p-3 rounded-lg">
                        <i class="fa fa-users text-secondary text-xl"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- 图表区域 - 统一卡片风格 -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
            <!-- 11月访问量图表 -->
            <div class="bg-white rounded-lg p-5 shadow-card card-transition hover:shadow-card-hover">
                <div class="flex items-center justify-between mb-4">
                    <h2 class="font-semibold text-lg text-neutral-700 flex items-center">
                        <i class="fa fa-line-chart text-primary mr-2"></i>
                        2017年11月访问量趋势
                    </h2>
                    <div class="flex space-x-2">
                        <button class="view-type-btn active px-2 py-1 text-xs rounded bg-primary/10 text-primary" data-view="daily">每日访问</button>
                        <button class="view-type-btn px-2 py-1 text-xs rounded bg-neutral-100 text-neutral-600" data-view="cumulative">累积访问</button>
                    </div>
                </div>
                <div class="chart-container h-[400px]">
                    <canvas id="visitsChart"></canvas>
                </div>
            </div>

            <!-- 购买量趋势图表 -->
            <div class="bg-white rounded-lg p-5 shadow-card card-transition hover:shadow-card-hover">
                <div class="flex items-center justify-between mb-4">
                    <h2 class="font-semibold text-lg text-neutral-700 flex items-center">
                        <i class="fa fa-shopping-cart text-primary mr-2"></i>
                        2017年11-12月购买量趋势
                    </h2>
                    <div class="flex space-x-2">
                        <button class="purchase-type-btn active px-2 py-1 text-xs rounded bg-primary/10 text-primary" data-month="11">11月</button>
                        <button class="purchase-type-btn px-2 py-1 text-xs rounded bg-neutral-100 text-neutral-600" data-month="12">12月</button>
                        <button class="purchase-type-btn px-2 py-1 text-xs rounded bg-neutral-100 text-neutral-600" data-month="both">对比</button>
                    </div>
                </div>
                <div class="chart-container h-[400px]">
                    <canvas id="purchasesChart"></canvas>
                </div>
            </div>
        </div>

        <!-- 行为分析图表 -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
            <!-- 行为分布环形图 -->
            <div class="bg-white rounded-lg p-5 shadow-card card-transition hover:shadow-card-hover">
                <h2 class="font-semibold text-lg text-neutral-700 flex items-center mb-4">
                    <i class="fa fa-pie-chart text-primary mr-2"></i>
                    用户行为分布
                </h2>
                <div class="chart-container h-[400px] flex items-center justify-center">
                    <canvas id="behaviorDistributionChart"></canvas>
                </div>
            </div>

            <!-- 行为时间分布堆叠图 -->
            <div class="bg-white rounded-lg p-5 shadow-card card-transition hover:shadow-card-hover">
                <div class="flex items-center justify-between mb-4">
                    <h2 class="font-semibold text-lg text-neutral-700 flex items-center">
                        <i class="fa fa-clock-o text-primary mr-2"></i>
                        用户活跃时间分布
                    </h2>
                    <div class="flex space-x-2">
                        <button class="time-dist-btn active px-2 py-1 text-xs rounded bg-primary/10 text-primary" data-view="hourly">小时分布</button>
                        <button class="time-dist-btn px-2 py-1 text-xs rounded bg-neutral-100 text-neutral-600" data-view="weekday">周别分布</button>
                    </div>
                </div>
                <div class="chart-container h-[400px]">
                    <canvas id="timeDistributionChart"></canvas>
                </div>
            </div>
        </div>

        <!-- 排名表格 -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
            <!-- 购买商品品类数用户排名 -->
            <div class="bg-white rounded-lg p-5 shadow-card card-transition hover:shadow-card-hover">
                <h2 class="font-semibold text-lg text-neutral-700 flex items-center mb-4">
                    <i class="fa fa-trophy text-primary mr-2"></i>
                    2017年11月购买商品品类数用户排名
                </h2>
                <div class="overflow-x-auto table-container">
                    <table class="min-w-full divide-y divide-neutral-200">
                        <thead>
                            <tr>
                                <th class="px-4 py-3 bg-neutral-100 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">排名</th>
                                <th class="px-4 py-3 bg-neutral-100 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">用户ID</th>
                                <th class="px-4 py-3 bg-neutral-100 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">购买商品品类数</th>
                            </tr>
                        </thead>
                        <tbody id="categoryRankingTable" class="bg-white divide-y divide-neutral-200">
                            <!-- 表格内容将通过JavaScript动态加载 -->
                            <tr>
                                <td colspan="3" class="px-4 py-8 text-center text-neutral-500">加载中...</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div class="mt-4 flex justify-center">
                    <button id="loadMoreCategories" class="text-primary hover:text-primary/80 text-sm flex items-center">
                        加载更多 <i class="fa fa-chevron-down ml-1 text-xs"></i>
                    </button>
                </div>
            </div>

            <!-- 购买数量前30%用户 -->
            <div class="bg-white rounded-lg p-5 shadow-card card-transition hover:shadow-card-hover">
                <div class="flex items-center justify-between mb-4">
                    <h2 class="font-semibold text-lg text-neutral-700 flex items-center">
                        <i class="fa fa-star text-primary mr-2"></i>
                        购买数量前30%的用户
                    </h2>
                    <div class="relative">
                        <select id="topUsersPercentage" class="bg-neutral-100 border border-neutral-200 text-neutral-700 rounded-md text-sm px-3 py-1.5 appearance-none focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none transition-all">
                            <option value="10">前10%</option>
                            <option value="20">前20%</option>
                            <option value="30" selected>前30%</option>
                            <option value="50">前50%</option>
                        </select>
                        <i class="fa fa-chevron-down absolute right-3 top-1/2 -translate-y-1/2 text-xs text-neutral-400 pointer-events-none"></i>
                    </div>
                </div>
                <div class="overflow-x-auto table-container">
                    <table class="min-w-full divide-y divide-neutral-200">
                        <thead>
                            <tr>
                                <th class="px-4 py-3 bg-neutral-100 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">排名</th>
                                <th class="px-4 py-3 bg-neutral-100 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">用户ID</th>
                                <th class="px-4 py-3 bg-neutral-100 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">购买数量</th>
                            </tr>
                        </thead>
                        <tbody id="topUsersTable" class="bg-white divide-y divide-neutral-200">
                            <!-- 表格内容将通过JavaScript动态加载 -->
                            <tr>
                                <td colspan="3" class="px-4 py-8 text-center text-neutral-500">加载中...</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div class="mt-4 flex justify-center">
                    <button id="loadMoreUsers" class="text-primary hover:text-primary/80 text-sm flex items-center">
                        加载更多 <i class="fa fa-chevron-down ml-1 text-xs"></i>
                    </button>
                </div>
            </div>
        </div>
    </main>

    <!-- 页脚 - 与RFM分析页面保持一致 -->
    <footer class="bg-white border-t border-neutral-200 py-8">
        <div class="container mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex flex-col md:flex-row justify-between items-center">
                <div class="mb-4 md:mb-0">
                    <p class="text-neutral-500 text-sm">© 2017 用户分析平台. 保留所有权利.</p>
                </div>
                <div class="flex space-x-6">
                    <a href="#" class="text-neutral-400 hover:text-primary transition-colors">
                        <i class="fa fa-question-circle"></i> 帮助中心
                    </a>
                    <a href="#" class="text-neutral-400 hover:text-primary transition-colors">
                        <i class="fa fa-file-text-o"></i> 使用文档
                    </a>
                    <a href="#" class="text-neutral-400 hover:text-primary transition-colors">
                        <i class="fa fa-envelope-o"></i> 联系我们
                    </a>
                </div>
            </div>
        </div>
    </footer>

    <!-- 加载中遮罩 - 与RFM分析页面保持一致的风格 -->
    <div id="loadingOverlay" class="fixed inset-0 bg-black/5 z-50 flex items-center justify-center hidden">
        <div class="bg-white p-6 rounded-lg flex items-center space-x-3 shadow-card">
            <div class="loader"></div>
            <span>数据加载中...</span>
        </div>
    </div>

    <script>
        // 全局变量
        let visitsChart, purchasesChart, behaviorDistributionChart, timeDistributionChart;
        let categoryRankingData = [], topUsersData = [];
        let currentCategoryPage = 1, currentUsersPage = 1;
        const itemsPerPage = 10;
        let autoRefreshInterval = null;

        // 显示错误消息 - 与RFM分析页面保持一致
        function showError(message) {
            const errorContainer = document.getElementById('error-container');
            const errorMessage = document.getElementById('error-message').querySelector('span');
            errorMessage.textContent = message;
            errorContainer.classList.remove('hidden');

            // 添加淡入效果
            errorContainer.classList.add('animate-fade-in');
            
            setTimeout(() => {
                // 添加淡出效果
                errorContainer.classList.add('opacity-0', 'transition-opacity', 'duration-500');
                setTimeout(() => {
                    errorContainer.classList.add('hidden');
                    errorContainer.classList.remove('opacity-0', 'transition-opacity', 'duration-500', 'animate-fade-in');
                }, 500);
            }, 5000);
        }

        // DOM加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化日期选择器
            const datePicker = flatpickr('#dateRangePicker', {
                mode: 'range',
                dateFormat: 'Y-m-d',
                locale: 'zh',
                defaultDate: ['2017-11-01', '2017-12-31'],
                maxDate: '2017-12-31',
                minDate: '2017-11-01'
            });

            // 初始化图表
            initCharts();

            // 加载数据
            loadAllData();

            // 绑定事件监听器
            bindEventListeners();
        });

        // 初始化图表
        function initCharts() {
            // 11月访问量图表
            const visitsCtx = document.getElementById('visitsChart').getContext('2d');
            visitsChart = new Chart(visitsCtx, {
                type: 'line',
                data: {
                    labels: [],
                    datasets: [
                        {
                            label: '每日访问量',
                            data: [],
                            borderColor: '#165DFF',
                            backgroundColor: 'rgba(22, 93, 255, 0.1)',
                            tension: 0.3,
                            fill: true
                        },
                        {
                            label: '累积访问量',
                            data: [],
                            borderColor: '#36CFC9',
                            backgroundColor: 'transparent',
                            tension: 0.3,
                            borderDash: [5, 5],
                            hidden: true
                        }
                    ]
                },
                options: getLineChartOptions('访问量')
            });

            // 购买量趋势图表
            const purchasesCtx = document.getElementById('purchasesChart').getContext('2d');
            purchasesChart = new Chart(purchasesCtx, {
                type: 'line',
                data: {
                    labels: [],
                    datasets: [
                        {
                            label: '11月每日购买量',
                            data: [],
                            borderColor: '#165DFF',
                            backgroundColor: 'rgba(22, 93, 255, 0.1)',
                            tension: 0.3,
                            fill: true
                        },
                        {
                            label: '11月累积购买量',
                            data: [],
                            borderColor: '#165DFF',
                            backgroundColor: 'transparent',
                            tension: 0.3,
                            borderDash: [5, 5]
                        },
                        {
                            label: '12月每日购买量',
                            data: [],
                            borderColor: '#FF7D00',
                            backgroundColor: 'rgba(255, 125, 0, 0.1)',
                            tension: 0.3,
                            fill: true,
                            hidden: true
                        },
                        {
                            label: '12月累积购买量',
                            data: [],
                            borderColor: '#FF7D00',
                            backgroundColor: 'transparent',
                            tension: 0.3,
                            borderDash: [5, 5],
                            hidden: true
                        }
                    ]
                },
                options: getLineChartOptions('购买量')
            });

            // 行为分布环形图
            const behaviorCtx = document.getElementById('behaviorDistributionChart').getContext('2d');
            behaviorDistributionChart = new Chart(behaviorCtx, {
                type: 'doughnut',
                data: {
                    labels: [],
                    datasets: [{
                        data: [],
                        backgroundColor: ['#165DFF', '#36CFC9', '#FF7D00', '#F53F3F'],
                        borderWidth: 0,
                        hoverOffset: 10
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'right',
                            labels: {
                                padding: 20,
                                usePointStyle: true,
                                pointStyle: 'circle'
                            }
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    const label = context.label || '';
                                    const value = context.raw || 0;
                                    const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                    const percentage = ((value / total) * 100).toFixed(1);
                                    return `${label}: ${value} (${percentage}%)`;
                                }
                            }
                        }
                    },
                    cutout: '65%',
                    animation: {
                        animateScale: true,
                        animateRotate: true
                    }
                }
            });

            // 时间分布图表
            const timeDistCtx = document.getElementById('timeDistributionChart').getContext('2d');
            timeDistributionChart = new Chart(timeDistCtx, {
                type: 'bar',
                data: {
                    labels: Array.from({length: 24}, (_, i) => `${i}时`),
                    datasets: [{
                        label: '行为数量',
                        data: Array(24).fill(0),
                        backgroundColor: '#165DFF',
                        borderRadius: 4
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        x: {
                            grid: {
                                display: false
                            }
                        },
                        y: {
                            beginAtZero: true,
                            title: {
                                display: true,
                                text: '行为数量'
                            }
                        }
                    },
                    plugins: {
                        legend: {
                            display: false
                        }
                    },
                    animation: {
                        duration: 1000
                    }
                }
            });
        }

        // 获取折线图通用配置
        function getLineChartOptions(yAxisTitle) {
            return {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    x: {
                        grid: {
                            display: false
                        }
                    },
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: yAxisTitle
                        }
                    }
                },
                plugins: {
                    legend: {
                        position: 'top',
                        labels: {
                            usePointStyle: true,
                            boxWidth: 6
                        }
                    },
                    tooltip: {
                        mode: 'index',
                        intersect: false
                    }
                },
                interaction: {
                    mode: 'nearest',
                    axis: 'x',
                    intersect: false
                },
                animation: {
                    duration: 1000
                }
            };
        }

        // 加载所有数据
        function loadAllData() {
            showLoading();

            // 并行加载所有数据
            Promise.all([
                loadDailyVisits(),
                loadCumulativePurchases(),
                loadBehaviorDistribution(),
                loadUserActiveTime(),
                loadCategoryRanking(),
                loadTopPurchaseUsers()
            ]).then(() => {
                hideLoading();
                updateLastUpdateTime();
            }).catch(error => {
                console.error('数据加载失败:', error);
                hideLoading();
                showError('数据加载失败: ' + error.message);
            });
        }

        // 加载每日访问量数据
        function loadDailyVisits() {
            return fetch('/api/daily_visits')
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP错误，状态码: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    if (!data || data.length === 0) return;

                    // 更新图表
                    const dates = data.map(item => item.date);
                    const visits = data.map(item => item.访问量);
                    const cumulativeVisits = data.map(item => item.累积访问量);

                    visitsChart.data.labels = dates;
                    visitsChart.data.datasets[0].data = visits;
                    visitsChart.data.datasets[1].data = cumulativeVisits;
                    visitsChart.update();

                    // 更新概览卡片
                    document.getElementById('totalVisits').textContent = cumulativeVisits[cumulativeVisits.length - 1].toLocaleString();
                    document.getElementById('visitsGrowth').textContent = '12.5% 较上月';
                });
        }

        // 加载累积购买量数据
        function loadCumulativePurchases() {
            return fetch('/api/cumulative_purchases?months=11,12&year=2017')
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP错误，状态码: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    if (!data) return;

                    // 处理11月数据
                    const novDailyData = data['2017-11_daily']?.daily_data || [];
                    const novTotal = data['2017-11_total'] || 0;

                    // 处理12月数据
                    const decDailyData = data['2017-12_daily']?.daily_data || [];
                    const decTotal = data['2017-12_total'] || 0;

                    // 更新图表
                    purchasesChart.data.labels = novDailyData.map(item => item.date);
                    purchasesChart.data.datasets[0].data = novDailyData.map(item => item.购买量);
                    purchasesChart.data.datasets[1].data = novDailyData.map(item => item.累积购买量);

                    // 调整12月日期标签以匹配图表
                    const decPurchases = decDailyData.map(item => item.购买量);
                    const decCumulative = decDailyData.map(item => item.累积购买量);

                    purchasesChart.data.datasets[2].data = decPurchases;
                    purchasesChart.data.datasets[3].data = decCumulative;

                    purchasesChart.update();

                    // 更新概览卡片
                    document.getElementById('novemberPurchases').textContent = novTotal.toLocaleString();
                    document.getElementById('decemberPurchases').textContent = decTotal.toLocaleString();

                    // 计算增长率
                    const novGrowth = ((novTotal / 10000) * 100).toFixed(1) + '%'; // 示例计算
                    const decGrowth = ((decTotal / novTotal - 1) * 100).toFixed(1) + '%';
                    document.getElementById('novPurchasesGrowth').textContent = novGrowth;
                    document.getElementById('decPurchasesGrowth').textContent = decGrowth;

                    // 更新活跃用户数（示例值）
                    document.getElementById('activeUsers').textContent = '987,994';
                    document.getElementById('usersGrowth').textContent = '3.2% 较上月';
                });
        }

        // 加载行为分布数据
        function loadBehaviorDistribution() {
            return fetch('/api/behavior_distribution')
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP错误，状态码: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    if (!data || data.length === 0) return;

                    // 转换行为类型为中文
                    const typeMap = {
                        'pv': '浏览',
                        'buy': '购买',
                        'cart': '加入购物车',
                        'fav': '收藏'
                    };

                    const labels = data.map(item => typeMap[item.行为类型] || item.行为类型);
                    const values = data.map(item => item.次数);

                    behaviorDistributionChart.data.labels = labels;
                    behaviorDistributionChart.data.datasets[0].data = values;
                    behaviorDistributionChart.update();
                });
        }

        // 加载用户活跃时间数据
        function loadUserActiveTime() {
            return fetch('/api/user_active_time')
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP错误，状态码: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    if (!data) return;

                    // 小时数据
                    const hourlyData = data.hourly || [];
                    const hourlyLabels = Array.from({length: 24}, (_, i) => `${i}时`);
                    const hourlyValues = Array(24).fill(0);

                    hourlyData.forEach(item => {
                        if (item.hour !== undefined && item.行为次数 !== undefined) {
                            hourlyValues[item.hour] = item.行为次数;
                        }
                    });

                    // 周别数据
                    const weekdayData = data.weekday || [];
                    const weekdayLabels = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
                    const weekdayValues = Array(7).fill(0);

                    weekdayData.forEach(item => {
                        const index = weekdayLabels.indexOf(item.周别);
                        if (index !== -1) {
                            weekdayValues[index] = item.行为次数;
                        }
                    });

                    // 存储在图表对象上以便切换
                    timeDistributionChart.hourlyData = { labels: hourlyLabels, values: hourlyValues };
                    timeDistributionChart.weekdayData = { labels: weekdayLabels, values: weekdayValues };

                    // 更新图表显示
                    timeDistributionChart.data.labels = hourlyLabels;
                    timeDistributionChart.data.datasets[0].data = hourlyValues;
                    timeDistributionChart.update();
                });
        }

        // 加载品类排名数据
        function loadCategoryRanking() {
            const year = document.getElementById('yearSelect').value;
            const month = document.getElementById('monthSelect').value;

            return fetch(`/api/category_ranking?year=${year}&month=${month}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP错误，状态码: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    if (!data || data.length === 0) return;

                    categoryRankingData = data;
                    currentCategoryPage = 1;
                    renderCategoryTable();
                });
        }

        // 加载顶部购买用户数据
        function loadTopPurchaseUsers() {
            const percentage = document.getElementById('topUsersPercentage').value;

            return fetch(`/api/top_purchase_users?percentage=${percentage}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP错误，状态码: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    if (!data || data.length === 0) return;

                    topUsersData = data;
                    currentUsersPage = 1;
                    renderTopUsersTable();
                });
        }

        // 渲染品类排名表格
        function renderCategoryTable() {
            const tableBody = document.getElementById('categoryRankingTable');
            const startIndex = (currentCategoryPage - 1) * itemsPerPage;
            const endIndex = startIndex + itemsPerPage;
            const pageData = categoryRankingData.slice(startIndex, endIndex);

            if (pageData.length === 0) {
                tableBody.innerHTML = '<tr><td colspan="3" class="px-4 py-8 text-center text-neutral-500">没有数据</td></tr>';
                return;
            }

            let html = '';
            pageData.forEach((item, index) => {
                const rank = startIndex + index + 1;
                html += `
                    <tr class="hover:bg-neutral-50 transition-colors">
                        <td class="px-4 py-3 whitespace-nowrap">
                            <div class="text-sm text-neutral-900">${rank}</div>
                        </td>
                        <td class="px-4 py-3 whitespace-nowrap">
                            <div class="text-sm text-neutral-900">${item.user_id}</div>
                        </td>
                        <td class="px-4 py-3 whitespace-nowrap">
                            <div class="text-sm text-neutral-900">${item.购买商品品类数}</div>
                        </td>
                    </tr>
                `;
            });

            tableBody.innerHTML = html;

            // 控制"加载更多"按钮显示
            document.getElementById('loadMoreCategories').style.display =
                endIndex < categoryRankingData.length ? 'flex' : 'none';
        }

        // 渲染顶部用户表格
        function renderTopUsersTable() {
            const tableBody = document.getElementById('topUsersTable');
            const startIndex = (currentUsersPage - 1) * itemsPerPage;
            const endIndex = startIndex + itemsPerPage;
            const pageData = topUsersData.slice(startIndex, endIndex);

            if (pageData.length === 0) {
                tableBody.innerHTML = '<tr><td colspan="3" class="px-4 py-8 text-center text-neutral-500">没有数据</td></tr>';
                return;
            }

            let html = '';
            pageData.forEach((item, index) => {
                const rank = startIndex + index + 1;
                html += `
                    <tr class="hover:bg-neutral-50 transition-colors">
                        <td class="px-4 py-3 whitespace-nowrap">
                            <div class="text-sm text-neutral-900">${rank}</div>
                        </td>
                        <td class="px-4 py-3 whitespace-nowrap">
                            <div class="text-sm text-neutral-900">${item.user_id}</div>
                        </td>
                        <td class="px-4 py-3 whitespace-nowrap">
                            <div class="text-sm text-neutral-900">${item.购买数量}</div>
                        </td>
                    </tr>
                `;
            });

            tableBody.innerHTML = html;

            // 控制"加载更多"按钮显示
            document.getElementById('loadMoreUsers').style.display =
                endIndex < topUsersData.length ? 'flex' : 'none';
        }

        // 更新最后更新时间
        function updateLastUpdateTime() {
            const now = new Date();
            const timeStr = now.toLocaleString();
            document.getElementById('lastUpdateTime').textContent = `最后更新: ${timeStr}`;
            //document.getElementById('footerUpdateTime').textContent = timeStr;
        }

        // 显示加载中遮罩
        function showLoading() {
            document.getElementById('loadingOverlay').classList.remove('hidden');
        }

        // 隐藏加载中遮罩
        function hideLoading() {
            document.getElementById('loadingOverlay').classList.add('hidden');
        }

        // 绑定事件监听器
        function bindEventListeners() {
            // 刷新按钮
            document.getElementById('refreshBtn').addEventListener('click', function() {
                loadAllData();
            });

            // 自动刷新间隔
            document.getElementById('refreshInterval').addEventListener('change', function() {
                const interval = parseInt(this.value);

                // 清除现有定时器
                if (autoRefreshInterval) {
                    clearInterval(autoRefreshInterval);
                    autoRefreshInterval = null;
                }

                // 设置新定时器
                if (interval > 0) {
                    autoRefreshInterval = setInterval(loadAllData, interval * 1000);
                }
            });

            // 视图切换按钮 - 访问量
            document.querySelectorAll('.view-type-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    document.querySelectorAll('.view-type-btn').forEach(b => {
                        b.classList.remove('active', 'bg-primary/10', 'text-primary');
                        b.classList.add('bg-neutral-100', 'text-neutral-600');
                    });

                    this.classList.add('active', 'bg-primary/10', 'text-primary');

                    const viewType = this.getAttribute('data-view');
                    if (viewType === 'daily') {
                        visitsChart.data.datasets[0].hidden = false;
                        visitsChart.data.datasets[1].hidden = true;
                    } else {
                        visitsChart.data.datasets[0].hidden = true;
                        visitsChart.data.datasets[1].hidden = false;
                    }
                    visitsChart.update();
                });
            });

            // 视图切换按钮 - 购买量
            document.querySelectorAll('.purchase-type-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    document.querySelectorAll('.purchase-type-btn').forEach(b => {
                        b.classList.remove('active', 'bg-primary/10', 'text-primary');
                        b.classList.add('bg-neutral-100', 'text-neutral-600');
                    });

                    this.classList.add('active', 'bg-primary/10', 'text-primary');

                    const month = this.getAttribute('data-month');
                    if (month === '11') {
                        purchasesChart.data.datasets[0].hidden = false;
                        purchasesChart.data.datasets[1].hidden = false;
                        purchasesChart.data.datasets[2].hidden = true;
                        purchasesChart.data.datasets[3].hidden = true;
                    } else if (month === '12') {
                        purchasesChart.data.datasets[0].hidden = true;
                        purchasesChart.data.datasets[1].hidden = true;
                        purchasesChart.data.datasets[2].hidden = false;
                        purchasesChart.data.datasets[3].hidden = false;
                    } else {
                        purchasesChart.data.datasets[0].hidden = false;
                        purchasesChart.data.datasets[1].hidden = true;
                        purchasesChart.data.datasets[2].hidden = false;
                        purchasesChart.data.datasets[3].hidden = true;
                    }
                    purchasesChart.update();
                });
            });

            // 时间分布视图切换
            document.querySelectorAll('.time-dist-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    document.querySelectorAll('.time-dist-btn').forEach(b => {
                        b.classList.remove('active', 'bg-primary/10', 'text-primary');
                        b.classList.add('bg-neutral-100', 'text-neutral-600');
                    });

                    this.classList.add('active', 'bg-primary/10', 'text-primary');

                    const viewType = this.getAttribute('data-view');
                    if (viewType === 'hourly' && timeDistributionChart.hourlyData) {
                        timeDistributionChart.data.labels = timeDistributionChart.hourlyData.labels;
                        timeDistributionChart.data.datasets[0].data = timeDistributionChart.hourlyData.values;
                    } else if (viewType === 'weekday' && timeDistributionChart.weekdayData) {
                        timeDistributionChart.data.labels = timeDistributionChart.weekdayData.labels;
                        timeDistributionChart.data.datasets[0].data = timeDistributionChart.weekdayData.values;
                    }
                    timeDistributionChart.update();
                });
            });

            // 加载更多品类排名
            document.getElementById('loadMoreCategories').addEventListener('click', function() {
                currentCategoryPage++;
                renderCategoryTable();
            });

            // 加载更多顶部用户
            document.getElementById('loadMoreUsers').addEventListener('click', function() {
                currentUsersPage++;
                renderTopUsersTable();
            });

            // 顶部用户百分比筛选
            document.getElementById('topUsersPercentage').addEventListener('change', function() {
                loadTopPurchaseUsers();
            });

            // 月份选择
            document.getElementById('monthSelect').addEventListener('change', function() {
                loadCategoryRanking();
            });

            // 年份选择
            document.getElementById('yearSelect').addEventListener('change', function() {
                loadCategoryRanking();
            });
        }
    </script>
</body>
</html>
